<template>
  <div class="container">
    <div class="container-left">
      <div>返回上一级</div>
      <div class="menu-list">
        <div
          class="menu-item"
          v-for="item in menuList"
          :key="item.key"
          @click="handleMenu(item)"
        >
          {{ item.name }}
        </div>
      </div>
      <div>
        <el-icon v-if="isExpand"><Fold /></el-icon>
        <el-icon v-else><Expand /></el-icon>
      </div>
    </div>
    <div class="container-center-right">
      <template v-if="fileUrl">
        <div class="container-center">
          <!-- 头部标注操作 -->
          <div class="container-center-operation-content">
            <div>{{ detailMsg.projectName }}-{{ detailMsg.templateName }}</div>
            <div class="container-center-operation-list">
              <div
                v-for="item in operationList"
                :key="item.key"
                @click="handleOperation(item)"
                class="container-center-operation-item"
              >
                <div v-if="item.name">{{ item.name }}</div>
                <div v-else-if="item.icon">{{ item.icon }}</div>
              </div>
            </div>
            <div>已标注区域: {{ rectList.length }}</div>
          </div>
          <!-- 标注区域 -->
          <Annotation
            ref="annotationRef"
            v-model:data="rectList"
            v-model:mouseOperationType="mouseOperationType"
            v-model:imageScale="imageScale"
            :srcUrl="fileUrl"
            :shortcutConfig="shortcutConfig"
            @mouseenter="blurAllInputs"
          />
        </div>
        <div class="container-right">
          <div class="container-right-search">
            <el-input v-model="searchText" placeholder="字段名称模糊搜索"></el-input>
            <el-icon style="margin-left: 8px"><Search /></el-icon>
          </div>
          <div class="rect-list">
            <div
              v-for="(item, index) in rectList"
              class="rect-item"
              v-show="!searchText || (searchText && item.label.includes(searchText))"
              :key="item.id"
              :class="[item.id == selectedElementId ? 'selected' : '']"
              :style="[item.id == selectedElementId && getSelectStyle(item)]"
              @mouseenter="handleMouseEnter(item)"
            >
              <div class="rect-item-header">
                <span>#{{ index + 1 }}</span>

                <!-- <el-dropdown placement="bottom-end" @command="handleDropdownCommand"> -->
                <el-dropdown placement="bottom-end">
                  <el-icon><More /></el-icon>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="remove">删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
              <div class="rect-item-field">
                <div class="field-name">字段名称</div>
                <el-input v-model="rectList[index].label"></el-input>
              </div>
              <div class="rect-item-field">
                <div class="field-name">格式处理</div>
                <el-select
                  v-model="rectList[index].formatType"
                  placeholder="请选择"
                  :show-arrow="false"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in formatProcessingList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </div>
              <!-- <div class="rect-item-field">
                <div class="field-name">x</div>
                <el-input v-model="rectList[index].x"></el-input>
              </div>
              <div class="rect-item-field">
                <div class="field-name">y</div>
                <el-input v-model="rectList[index].y"></el-input>
              </div> -->
              <div class="rect-item-field">
                <div class="field-name">测试结果</div>
                <el-input v-model="rectList[index].result"></el-input>
              </div>
            </div>
          </div>
          <div class="container-right-bottom">
            <div class="container-right-bottom-btn container-right-bottom-test-btn">
              批量测试
            </div>

            <div
              class="container-right-bottom-btn container-right-bottom-save-btn"
              @click="save"
            >
              保存
            </div>
          </div>
        </div>
      </template>
      <div v-else></div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, computed, onMounted } from "vue";
import Annotation from "@/components/annotation.vue";
// import Annotation from "@/components/annotation copy.vue";
import { Search, More, Expand, Fold } from "@element-plus/icons-vue";

function hexToRgb(hex, alpha = 0.1) {
  // 去除可能存在的 # 前缀
  hex = hex.replace(/^#/, "");

  // 处理简写形式，如 #fff
  if (hex.length === 3) {
    hex = hex
      .split("")
      .map((c) => c + c)
      .join("");
  }

  // 解析十六进制值
  const bigint = parseInt(hex, 16);
  const r = (bigint >> 16) & 255;
  const g = (bigint >> 8) & 255;
  const b = bigint & 255;

  // 返回 rgba 格式字符串
  return `rgba(${r}, ${g}, ${b}, ${alpha})`;
}
const fileUrl = ref("@/assets/cc.jpg");
// const fileUrl = ref("@/assets/row.png");
// import Annotation from "@/components/annotation-origin.vue";
const mouseOperationType = ref("mouseSelect");
const imageScale = ref(1);
const annotationRef = ref(null);
const detailMsg = ref({
  id: "",
  projectName: "项目名称",
  templateName: "模板名称",
});
const shortcutConfig = ref({
  readRangeMarker: {
    key: "n",
    fill: "#ef4c4c",
  },
  unReadRangeMarker: {
    key: "r",
    fill: "#40ff40",
  },
});
const isExpand = ref(true);

const menuList = ref([
  {
    key: "mouseSelect",
    name: "鼠标选择",
  },
  {
    key: "batchSelect",

    name: "批量选择",
  },
  {
    key: "standardSetting",
    name: "标准设置",
  },
  {
    key: "exportSetting",
    name: "导出设置",
  },
]);

const operationList = ref([
  {
    key: "prev",
    name: "上一个",
    icon: "",
  },
  {
    key: "next",

    name: "下一个",
    icon: "",
  },
  {
    key: "intro",
    name: "操作说明",
    icon: "",
  },
  {
    key: "revoke",
    name: "撤销",
    icon: "",
  },
  {
    key: "cancelRevoke",
    name: "取消撤销",
    icon: "",
  },
  {
    key: "reset",
    name: "重置",
    icon: "",
  },
  {
    key: "magnify",
    name: "放大",
    icon: "",
  },
  {
    key: "reduce",
    name: "缩小",
    icon: "",
  },
]);

const formatProcessingList = ref([
  {
    label: "格式处理1",
    value: "1",
  },
  {
    label: "格式处理2",
    value: "2",
  },
  {
    label: "格式处理3",
    value: "3",
  },
]);
const searchText = ref("");

// const filterRectList = computed(() => {
//   if (searchText.value) {
//     return rectList.value.filter((item) => item.label.includes(searchText.value));
//   }
//   return rectList.value;
// });
function getSelectStyle(rectItem) {
  return {
    background: hexToRgb(shortcutConfig.value[rectItem.rectType].fill),
    borderColor: shortcutConfig.value[rectItem.rectType].fill,
  };
}

const rectList = ref([
  // {
  //   type: "rect",
  //   id: "element_1755409174402_nhce73bx1s",
  //   rectType: "unReadRangeMarker",
  //   x: 100,
  //   y: 0,
  //   width: 436,
  //   height: 241,
  //   label: "",
  //   desc: "",
  //   formatType: "",
  //   result: "",
  //   position: [100, 152, 625.640625, 152, 625.640625, 393, 100, 393],
  // },
]);

onMounted(() => {
  console.log("rectList.value--", rectList.value);
  setTimeout(() => {
    rectList.value = JSON.parse(localStorage.getItem("rectList")) || [
      {
        type: "rect",
        id: "element_1755409174402_nhce73bx6",
        rectType: "readRangeMarker",
        x: 0,
        y: 0,
        width: 436,
        height: 241,
        label: "",
        desc: "",
        formatType: "",
        result: "",
        position: [0, 152, 625.640625, 152, 625.640625, 393, 0, 393],
      },
      {
        type: "rect",
        id: "element_1755409174402_nhce73bx61",
        rectType: "readRangeMarker",
        x: 2027.60107421875,
        y: 220.81103515625,
        width: 2397.430908203125 - 2027.60107421875,
        height: 70,
        label: "",
        desc: "",
        formatType: "",
        result: "",
        position: [
          2027.60107421875,
          220.81103515625,
          2397.430908203125,
          221.28485107421875,
          2396.90185546875,
          297.56475830078125,
          2027.1673583984375,
          297.0493469238281,
        ],
      },
      {
        type: "rect",
        id: "element_1755409174402_nhce73bx62",
        rectType: "readRangeMarker",
        x: 468.2182922363281,
        y: 305.75103759765625,
        width: 1094.1683349609375 - 468.2182922363281,
        height: 395.3443603515625 - 305.75103759765625,
        label: "",
        desc: "",
        formatType: "",
        result: "",
        position: [
          468.2182922363281,
          305.75103759765625,
          1094.1683349609375,
          306.63372802734375,
          1093.9405517578125,
          396.30999755859375,
          468.17987060546875,
          395.3443603515625,
        ],
      },
    ];
  }, 0);
});

// 鼠标移入选中当前矩形
const handleMouseEnter = (item) => {
  console.log("item--", item);
  console.log("annotationRef.value.allElements--", annotationRef.value.allElements);
  const hoverElement = annotationRef.value.allElements.find(
    (ele) => ele.data("elementId") == item.id
  );
  console.log("hoverElement--", hoverElement);
  annotationRef.value.handleHoverPreview(
    {
      x: item.x,
      y: item.y,
    },
    hoverElement
  );
};

const selectedElementId = computed(() => {
  return annotationRef.value?.hoveredElement?.data("elementId");
});

const handleMenu = (item) => {
  switch (item.key) {
    case "mouseSelect":
      break;
    case "batchSelect":
      break;
    case "standardSetting":
      break;
    case "exportSetting":
      break;
    case "revoke":
      undoLastAction();
      break;
    case "cancelRevoke":
      cancelUndo();
      break;
    case "reset":
      break;
    default:
      break;
  }
};

const handleOperation = (item) => {
  switch (item.key) {
    case "prev":
      console.log("切换");

      break;
    case "next":
      break;
    case "intro":
      break;
    case "revoke":
      undoLastAction();
      break;
    case "cancelRevoke":
      cancelUndo();
      break;
    case "reset":
      annotationRef.value?.resetViewport()
      break;
    default:
      break;
  }
};

watch(
  () => rectList.value,
  (newVal) => {
    console.log("newVal---", newVal);
  },
  { immediate: true, deep: true }
);

const hasHistory = computed(() => {
  return hasUndoStack || hasRedoStack;
});
const hasUndoStack = computed(() => {
  return !!annotationRef.value?.historyOperationList?.undoStack?.length;
});
const hasRedoStack = computed(() => {
  return !!annotationRef.value?.historyOperationList?.redoStack?.length;
});

const undoLastAction = () => {
  if (hasUndoStack.value) {
    annotationRef.value.undoLastAction();
  }
};
const cancelUndo = () => {
  if (hasRedoStack.value) {
    annotationRef.value.cancelUndo();
  }
};

// 添加函数用于取消所有输入框的聚焦状态
const blurAllInputs = () => {
  const inputs = document.querySelectorAll("input, select");
  inputs.forEach((input) => input.blur());
};

const save = () => {
  const saveData = rectList.value.map((item) => {
    return {
      ...item,
      x: item.x / imageScale.value,
      y: item.y / imageScale.value,
      width: item.width / imageScale.value,
      height: item.height / imageScale.value,
    };
  });
  localStorage.setItem("rectList", JSON.stringify(saveData));

  console.log("saveData--", saveData);
};
</script>
<style lang="scss" scoped>
.container {
  height: 100vh;
  display: flex;
}
.container-left {
  width: 200px;
  height: 100%;
  background-color: #fff;
  padding: 12px;
  border-right: 1px solid #d1d5db;

  .menu-list {
    flex: 1;
  }
}
.container-center-right {
  flex: 1;
  display: flex;
}
.container-center {
  flex: 1;
  background-color: #f9fafb;
  display: flex;
  flex-direction: column;
  .container-center-operation-content {
    display: flex;
    background: #fff;
    padding: 12px;
  }
  .container-center-operation-list {
    flex: 1;
    display: flex;
    justify-content: center;
    gap: 10px;
    .container-center-operation-item {
      cursor: pointer;
    }
  }
}
.container-right {
  width: 280px;
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  // padding: 12px;
  overflow-y: hidden;
  border-left: 1px solid #d1d5db;
  .container-right-search {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    margin: 12px;
  }
}

.rect-list {
  flex: 1;
  overflow-y: auto;
  padding: 0 12px 12px;
  .rect-item {
    border-radius: 8px;
    border: 1px solid #d1d5db;
    margin-bottom: 8px;
    padding: 10px 16px;
    color: #515866;
    &.selected {
      border-color: rgb(239, 68, 68);
      background: rgb(239, 68, 68, 0.2);
    }

    .rect-item-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .rect-item-field {
      margin-bottom: 10px;
    }
    .field-name {
      font-size: 14px;
    }

    .label {
      color: #424b5a;
    }
    .value {
      color: #606266;
    }
  }
}

.container-right-bottom {
  display: flex;
  padding: 12px;
  border-top: 1px solid #d1d5db;

  .container-right-bottom-btn {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 6px;
    border-radius: 4px;
    cursor: pointer;
  }
  .container-right-bottom-test-btn {
    flex: 1;
    background: #fff;
    border: 1px solid #3662ec;
    color: #3662ec;
    margin-right: 10px;
  }
  .container-right-bottom-save-btn {
    flex: 1;
    background: #3662ec;
    color: #fff;
  }
}
</style>
